<?php
class OrdersController extends AppController {

	var $name = 'Orders';
	var $helpers = array('Html', 'Form');

	function index() {
		$this->Order->recursive = 0;
		
		$ordertypes = $this->Order->Ordertype->find('list');
		$this->set(compact('ordertypes'));
		
		$this->set('orders', $this->paginate());
		
		// для установки факультета и курса
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set(compact('facultets'));
		$this->loadModel('Profession');
		$selectedprofessions = $this->Profession->find('list');
		$this->set(compact('selectedprofessions'));
		$this->loadModel('Course');
		$selectedcourses = $this->Course->find('list');
		$this->set(compact('selectedcourses'));
		$this->loadModel('Studentgroup');
		$selectedgroups = $this->Studentgroup->find('list');
		$this->set(compact('selectedgroups'));
		// вывод установки если есть
		// иницилизация переменных настроек
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = '';
		if ($this->Session->check('Settings')){
			$settings = $this->Session->read('Settings');
			$selectedfacultet = $settings['Settings']['selectedfacultet'];
			$selectedprofession = $settings['Settings']['selectedprofession'];
			$selectedcourse = $settings['Settings']['selectedcourse'];
			$selectedgroup = $settings['Settings']['selectedgroup'];
		}
		$this->set(compact('selectedfacultet', $selectedfacultet));
		$this->set(compact('selectedprofession', $selectedprofession));
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
		
		$this->loadModel('Student');
		$this->loadModel('Studentinfo');
		
		if ($selectedgroup){
			$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroup)));
			$studentslist = array();
			foreach ($students as $student):
			$studentslist[$student['Student']['id']]= $student['Student']['lastname'].' '.$student['Student']['firstname'].' '.$student['Student']['surname'];
			endforeach;
		} else {
			$studentslist = '';
		}
		$this->set('students', $studentslist);
		
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Order', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('order', $this->Order->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Order->create();
			if ($this->Order->save($this->data)) {
				$this->Session->setFlash(__('The Order has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The Order could not be saved. Please, try again.', true));
			}
		}
		$ordertypes = $this->Order->Ordertype->find('list');
		$students = $this->Order->Student->find('list');
		$this->set(compact('ordertypes', 'students'));
	}

	function edit($id = null) {
		
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Order', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Order->save($this->data)) {
				$this->Session->setFlash(__('Приказ был изменен', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The Order could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Order->read(null, $id);
		}
		//debug($this->data);
		$ordertypes = $this->Order->Ordertype->find('list');
		$student = $this->data['Student'];
		$this->set(compact('ordertypes','student'));
		
		// загружаем модели чтобы вывести инфо по студенту
		$this->loadModel('Course');
		$this->loadmodel('Profession');
		$professions = $this->Profession->find('list');
		$this->set(compact('professions'));
		$this->loadModel('Learningtype');
		$learningtypes = $this->Learningtype->find('list');
		$this->set(compact('learningtypes'));
		$this->loadmodel('Studentstate');
		$studentstates = $this->Studentstate->find('list');
		$this->set(compact('studentstates'));
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this->set(compact('learningforms'));
		
		$this->loadmodel('Studentgroup');
		
		$studentgroup = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.id' => $student['studentgroup_id']), 'recursive' => -1));
		$this->set(compact('studentgroup'));
		$course = $this->Course->find('all', array('conditions' => array('Course.id' => $studentgroup[0]['Studentgroup']['course_id']), 'recursive' => -1));
		$this->set(compact('course'));
		
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Order', true));
			$this->redirect(array('action' => 'index'));
		}
		if ($this->Order->del($id)) {
			$this->Session->setFlash(__('Order deleted', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('The Order could not be deleted. Please, try again.', true));
		$this->redirect(array('action' => 'index'));
	}
	
	function addorder() {
		$ordertypes = $this->Order->Ordertype->find('list');
		$this->set(compact('ordertypes'));
		
		// для установки факультета и курса
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set(compact('facultets'));
		$this->loadModel('Profession');
		$selectedprofessions = $this->Profession->find('list');
		$this->set(compact('selectedprofessions'));
		$this->loadModel('Course');
		$selectedcourses = $this->Course->find('list');
		$this->set(compact('selectedcourses'));
		$this->loadModel('Studentgroup');
		$selectedgroups = $this->Studentgroup->find('list');
		$this->set(compact('selectedgroups'));
		// вывод установки если есть
		// иницилизация переменных настроек
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = '';
		if ($this->Session->check('Settings')){
			$settings = $this->Session->read('Settings');
			$selectedfacultet = $settings['Settings']['selectedfacultet'];
			$selectedprofession = $settings['Settings']['selectedprofession'];
			$selectedcourse = $settings['Settings']['selectedcourse'];
			$selectedgroup = $settings['Settings']['selectedgroup'];
		}
		$this->set(compact('selectedfacultet', $selectedfacultet));
		$this->set(compact('selectedprofession', $selectedprofession));
		$this->set(compact('selectedcourse', $selectedcourse));
		$this->set(compact('selectedgroup', $selectedgroup));
		
		// устанавливаем true если приказ групповой
		$is_group = false;
		$ids = array();
		// подключаем модели
		$this->loadModel('Studentgroup');
		$this->loadModel('Student');
		//$this->loadModel('Studentinfo');
		
		
		if (($selectedgroup =='') && $selectedcourse && $selectedprofession && $selectedfacultet) {
			$is_group = true;
			$groups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourse), 'recursive' => -1));
			//debug ($groups);
			foreach ($groups as $group):
				$ids[$group['Studentgroup']['id']] = $group['Studentgroup']['name'];
			endforeach;
		} else if ($selectedgroup && $selectedcourse && $selectedprofession && $selectedfacultet){
			$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroup)));
			
			foreach ($students as $student):
			$ids[$student['Student']['id']]= $student['Student']['lastname'].' '.$student['Student']['firstname'].' '.$student['Student']['surname'];
			endforeach;
		} else {
			$ids = '';
		}
		//debug ($ids);
		// отправляем id 
		$this->set('ids', $ids);
		// отправляем логическое поле изи группы или студенты
		$this->set ('is_group', $is_group);
	}
	
	function putorder () {
		if (!empty($this->data)) {
			// подключаем модели
			$this->loadModel('Student');
			$this->loadModel('Ordertype');
			$ordertypes = $this->Order->Ordertype->find('list');
			$this->set(compact('ordertypes'));			
			
			//debug ($this->data);
			// обрабатываем переменные
					
			// тип приказа
			$ordertype_id = $this->data['Order']['ordertype_id'];	
			// номер приказа
			$order_number = $this->data['Order']['number'];			
			// год приказа
			$order_year = $this->data['Order']['year']['year'];
			// месяц приказа
			$order_month = $this->data['Order']['month']['month'];
			// день приказа
			$order_day = $this->data['Order']['day']['day'];
			// информация по приказу			
			$order_info = $this->data['Order']['order_info'];
			// id из списка ids
			$id = $this->data['Order']['id'];

			// если приказ по группе
			if ($this->data['Order']['is_group']){

				// выбираем всех студентов которые имеют состояние учится (id = 1)
				$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $id, /* 'Student.studentstate_id' => 1 */), 'recursive' => -1));
				//debug ($students);
				foreach($students as $student):
					$this->Order->create();
					$neworder = array('Order' => array('ordertype_id' => $ordertype_id,
																	'number' => $order_number,
																	'date' => $order_year.'-'.$order_month.'-'.$order_day,
																	'student_id' => $student['Student']['id'],
																	'order_info' => $order_info	));
					$this->Order->save($neworder);				
				endforeach;
			} 
			// если приказ по студенту
				else {
				$this->Order->create();
				$neworder = array('Order' => array('ordertype_id' => $ordertype_id,
												'number' => $order_number,
												'date' => $order_year.'-'.$order_month.'-'.$order_day,
												'student_id' => $id,
												'order_info' => $order_info	));
				$this->Order->save($neworder);
				$students = $this->Student->find('all', array('conditions' => array('Student.id' => $id, /* 'Student.studentstate_id' => 1 */), 'recursive' => -1));
			}
			$this->set('students', $students);
			$this->set('neworder', $neworder);
		}
	}

	/*
	 * 	поиск по приказам
	 */
	function searchorder() {
		if  (!empty($this->data)) {
			// год приказа
			$order_year = $this->data['Order']['year']['year'];
			// месяц приказа
			$order_month = $this->data['Order']['month']['month'];
			// день приказа
			$order_day = $this->data['Order']['day']['day'];
			// номер приказа
			$order_number = $this->data['Order']['number'];
			// тип приказа
			$ordertype_id = $this->data['Order']['ordertype_id'];
			// доп информация в приказе
			$order_info = $this->data['Order']['order_info'];
			// определяем формат результата
			$format = $this->data['Order']['format'];
			
			// создаем массив поисковых ключей
			$search_conditions = array();		
			if ($ordertype_id){
				array_push($search_conditions, array('Order.ordertype_id' => $ordertype_id));
			}	
			if ($order_number) {
				array_push($search_conditions, array('Order.number LIKE ' => $order_number.'%'));
			}
			// многокомпонентное условие даты приказа
			if ($order_year && $order_month && $order_day){
				$orderdate = $order_year.'-'.$order_month.'-'.$order_day;
				array_push($search_conditions, array('Order.date LIKE ' => $orderdate.'%'));
			} else if ($order_year && $order_month && !$order_day) {
				$orderdate = $order_year.'-'.$order_month;
				array_push($search_conditions, array('Order.date LIKE ' => $orderdate.'%'));
			} else if (!$order_year && $order_month && $order_day) {
				$orderdate = $order_month.'-'.$order_day;
				array_push($search_conditions, array('Order.date LIKE ' => '%'.$orderdate.'%'));
			} else if ($order_year && !$order_month && $order_day) {
				$orderdate = $order_year.'-%-'.$order_day;
				array_push($search_conditions, array('Order.date LIKE ' => $orderdate));
			} else if ($order_year && !$order_month && !$order_day) {
				$orderdate = $order_year;
				array_push($search_conditions, array('Order.date LIKE ' => $orderdate.'%'));
			} else if (!$order_year && $order_month && !$order_day){
				$orderdate = $order_month;
				array_push($search_conditions, array('Order.date LIKE ' => '%-'.$orderdate.'-%'));
			} else if (!$order_year && !$order_month && $order_day) {
				$orderdate = '-'.$order_day;
				array_push($search_conditions, array('Order.date LIKE ' => '%'.$orderdate));
			}
			// конец условия даты приказа
			
			if ($order_info) {
				array_push($search_conditions, array('Order.order_info LIKE ' => '%'.$order_info.'%'));
			}
			// закончили разбирать условие поиска
			$orders = $this->Order->find('all', array('conditions' => $search_conditions));
			
			$this->set('orders', $orders);
			
			$this->set('format', $format);
			// если выводим в файл значит подключить blank шаблон
			if (($format == 1) || ($format == 2)){
				$this->render('/', 'blank', 'searchorder');
			}			
		}
	}
}
?>